	package ca.etsmtl.log430.lab3;

	import java.io.PipedReader;
	import java.io.PipedWriter;
/**
 * ce filtre ne laisse passer que les etats differents de celui fourni en parametre
 * revient a declarer un stateFilter avec null pour la output1 et la sortie pour la output2
 * @author fafa
 *
 */
public class StateNotEqualFilter extends Thread{

		// Declarations

		boolean done;

		String severity;
		PipedReader inputPipe = new PipedReader();
		PipedWriter outputPipe = new PipedWriter();

		public StateNotEqualFilter(String severity, PipedWriter inputPipe,
				PipedWriter outputPipe) {

			this.severity = severity;

			try {

				// Connect inputPipe
				this.inputPipe.connect(inputPipe);
				System.out.println("StateFilter " + severity
						+ ":: connected to upstream filter.");

				// Connect outputPipe
				this.outputPipe = outputPipe;
				System.out.println("StateFilter " + severity
						+ ":: connected to downstream filter.");

			} catch (Exception Error) {

				System.out.println("StateFilter " + severity
						+ ":: Error connecting to other filters.");

			} // try/catch

		} // Constructor

		// This is the method that is called when the thread is started
		public void run() {

			// Declarations

			char[] characterValue = new char[1];
			// char array is required to turn char into a string
			String lineOfText = "";
			// string is required to look for the keyword
			int integerCharacter; // the integer value read from the pipe

			try {

				done = false;

				while (!done) {

					integerCharacter = inputPipe.read();
					characterValue[0] = (char) integerCharacter;

					if (integerCharacter == -1) { // pipe is closed

						done = true;

					} else {

						if (integerCharacter == '\n') { // end of line

							System.out.println("StateFilter " + severity
									+ ":: received: " + lineOfText + ".");

							if (lineOfText.indexOf(severity) == -1) {		//si RIS n y est pas alors on laisse passer

								System.out.println("StateFilter "
										+ severity + ":: sending: "
										+ lineOfText + " to output pipe.");
								lineOfText += new String(characterValue);
								outputPipe
										.write(lineOfText, 0, lineOfText.length());
								outputPipe.flush();

							} // if

							lineOfText = "";

						} else {

							lineOfText += new String(characterValue);

						} // if //

					} // if

				} // while

			} catch (Exception error) {

				System.out.println("StateFilter::" + severity
						+ " Interrupted.");

			} // try/catch

			try {

				inputPipe.close();
				System.out.println("StateFilter " + severity
						+ ":: input pipe closed.");

				outputPipe.close();
				System.out.println("StateFilter " + severity
						+ ":: output pipe closed.");

			} catch (Exception error) {

				System.out.println("StateFilter " + severity
						+ ":: Error closing pipes.");

			} // try/catch

		} // run
}
